//
//  MHPisctureHeight.m
//  ManHua
//
//  Created by 赵永泉 on 15/10/31.
//  Copyright © 2015年 蓝欧科技. All rights reserved.
//

#import "MHPisctureHeight.h"
#import "UIImage+Addiction.h"
#import <SDWebImageManager.h>

@implementation MHPisctureHeight

- (instancetype)initWithPictureUrl:(NSString *)url
{
    if (self = [super init]) {
        _pictureUrl = url;
        _pictureHeight = Width;
    }
    return self;
}

- (UIImage *)picture
{
    if (_picture == nil) {
        NSString *picturURL = self.pictureUrl;
        for(int i = 0; i< [picturURL length]; i++){
            int a = [picturURL characterAtIndex:i];
            if( a > 0x4e00 && a < 0x9fff)
            {
                picturURL = [picturURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                break;
            }
        }
        NSURL *url = [NSURL URLWithString:picturURL];
        SDWebImageManager *manager = [[SDWebImageManager alloc]init];
        __weak MHPisctureHeight *test = self;
        [manager downloadImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            if (!error) {
                _picture = image;
                if (CGSizeEqualToSize(image.size, CGSizeZero)) {
                    _pictureHeight = 0;
                }
                else
                    _pictureHeight = image.size.height / image.size.width * Height;
                if (test.reloadCellBlock != nil) {
                    test.reloadCellBlock();
                }
            }
            else
            {
                NSLog(@"%@", error.localizedDescription);
            }
        }];
    }
    return _picture;
}

+ (instancetype)pisctureHeightWithPictureUrl:(NSString *)url
{
    return [[self alloc]initWithPictureUrl:url];
}

@end
